package com.jswzc.common.api.service.wxTemplate;


import com.jswzc.api.service.wxTemplate.WxTemplateServiceI;
import com.jswzc.common.api.model.Wx.WxTemplateConfig;
import com.jswzc.dao.mdao.DaoSupport;
import com.jswzc.framework.util.HttpRequest;
import com.jswzc.framework.util.HttpRequestUtil;
import com.jswzc.framework.util.StringUtil;
import com.jswzc.framework.util.UuidUtil;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by liujiajia on 2017/5/9.
 */
@Service("wxTemplateService")
public class WxTemplateServiceImpl implements WxTemplateServiceI {

    @Resource(name = "daoSupport")
    private DaoSupport dao;


    @Override
    public String getAllPrivateTemplateByAccessToken(String accessToken){
        String requestUrl= WxTemplateConfig.get_all_private_template_url.replace("ACCESS_TOKEN",accessToken);
        JSONObject jsonObject = new JSONObject();
        jsonObject = HttpRequestUtil.httpRequest(requestUrl,"GET",null);
        System.out.print(jsonObject.toString());
        return jsonObject.toString();
    }

    @Override
    public String findTemplateId(String app_id,String accessToken,String template_id_short) throws Exception {

        //查询appid对应short是否存在template 如果不存在调用新增接口
        Map<String,Object> param = new HashMap<>();
        param.put("app_id",app_id);
        param.put("template_id_short",template_id_short);
        String template_id = (String)dao.findForObject("WxTemplateDao.findTemplateIdByAppid",param);

        if(StringUtils.isBlank(template_id)){
            String requestUrl = WxTemplateConfig.api_add_template_url.replace("ACCESS_TOKEN",accessToken);
            JSONObject jsonObject = new JSONObject();
            jsonObject = HttpRequestUtil.httpRequest(requestUrl,"POST"," {\n" +
                    "\"template_id_short\":\""+template_id_short+"\"\n" +
                    "}");

            System.out.print(jsonObject.toString());
            String errcode = jsonObject.getString("errcode");
            if(errcode.equals("0")){
                template_id=jsonObject.get("template_id").toString();
                param.put("template_id",template_id);
                param.put("id", UuidUtil.get32UUID());
                dao.save("WxTemplateDao.saveWxTemplate",param);
            }else{
                template_id="";
            }
        }
        return template_id;
    }

    @Override
    public String sendTemplate(String app_id,String accessToken,String open_id,String template_id_short,String link_url, String content) throws Exception {
        String result="";
        //1.通过微信模版短号 查询模版ID
        String template_id =findTemplateId(app_id,accessToken,template_id_short);
        if (!StringUtil.isNullOrEmpty(template_id)){
            String requestUrl = WxTemplateConfig.send_template_url.replace("ACCESS_TOKEN",accessToken);
            Map<String,Object> templateMap =new HashMap<>();
            templateMap.put("touser",open_id);
            templateMap.put("template_id",template_id);
            templateMap.put("url",link_url);
            templateMap.put("topcolor","#FF0000");
            templateMap.put("data",content);

            String sendString = "{"
                    +"\"touser\":"+"\""+open_id+"\","
                    +"\"template_id\":"+"\""+template_id+"\","
                    +"\"url\":"+"\""+link_url+"\","
                    +"\"topcolor\":"+"\"#FF0000\","
                    +"\"data\":"+""+content
                    +"}";

            System.out.print("输出str===>"+sendString);
            JSONObject sendObject =HttpRequestUtil.httpRequest(requestUrl,"POST",sendString);
            result =sendObject.toString();
            //HttpRequest.sendPost(requestUrl,sendString);
        }

        return result;
    }


    /**
     * 客服消息（文本消息）
     * @param open_id 消息接收方微信open_id
     * @param accessToken 接口调用凭证
     * @param content 文本内容
     * @return
     * @throws Exception
     */
    @Override
    public Map<String,Object> customSend(String open_id,String accessToken, String content) throws Exception {
        Map<String,Object> jsonObject = new HashMap<>();
        try {
            String jsonString="{\"touser\":\""+open_id+"\","+
                    "\"msgtype\":\"text\","+
                    "\"text\":{"+
                    "\"content\": \""+content+"\"" +
                    "}"+
                    "}";
            String requestUrl = WxTemplateConfig.send_custom_url.replace("ACCESS_TOKEN",accessToken);
            jsonObject = HttpRequestUtil.httpRequest(requestUrl, "POST", jsonString);

        } catch (Exception e) {
            String msg = e.getMessage();
            if(msg.length()>100){
                msg = msg.substring(0, 99);
            }
            jsonObject.put("errmsg", msg);
        }
        System.out.println(jsonObject);
        return jsonObject;
    }

}
